package de.slothsoft.wasbinich.swingclient.res;

import java.awt.Dimension;
import java.awt.Image;
import java.net.URL;
import java.util.Map;
import java.util.TreeMap;

import javax.swing.ImageIcon;

import de.slothsoft.wasbinich.swingclient.io.ImageUtil;

@SuppressWarnings("nls")
public final class Images {

    public static final String APPLICATION_ICON = "application.png";
    public static final String OBJECT_TOAD = "happy_toad.png";
    public static final String TOOLBAR_BACK = "navigation_upwards.png";
    public static final String TOOLBAR_CREATE = "create.png";
    public static final String TOOLBAR_EDIT = "edit.png";
    public static final String TOOLBAR_SAVE = "save.png";
    public static final String TOOLBAR_DELETE = "delete.png";

    private static final Map<String, ImageIcon> images = new TreeMap<>();

    public static ImageIcon get(String imageName) {
	if (imageName == null)
	    return null;
	ImageIcon icon = images.get(imageName);

	if (icon == null) {
	    URL url = Images.class.getResource("gfx/" + imageName);//$NON-NLS-1$
	    if (url == null)
		return null;
	    icon = new ImageIcon(url);
	    images.put(imageName, icon);
	}
	return icon;
    }

    public static ImageIcon getPictureFromData(String pictureData) {
	return getPictureFromData(pictureData, null);
    }

    public static ImageIcon getPictureFromData(String pictureData, Dimension resizeDimension) {
	if (pictureData == null)
	    return null;
	String key = getKey(pictureData, resizeDimension);

	ImageIcon icon = images.get(key);
	if (icon == null) {
	    Image image = ImageUtil.convertStringToImage(pictureData);
	    if (resizeDimension == null || resizeDimension.width == 0 || resizeDimension.height == 0) {
		icon = new ImageIcon(image);
	    } else {
		icon = new ImageIcon(ImageUtil.resize(image, resizeDimension.width, resizeDimension.height));
	    }
	    images.put(key, icon);
	}
	return icon;
    }

    private static String getKey(String pictureData, Dimension resizeDimension) {
	return pictureData.hashCode() + "-"
		+ (resizeDimension == null ? "0x0" : resizeDimension.width + "x" + resizeDimension.height);
    }

    private Images() {
	// hide me
    }
}
